package com.example.guestbookmybatis.controller;


import com.example.guestbookmybatis.domain.Message;
import com.example.guestbookmybatis.service.BookService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

//    访问留言本首页
    @RequestMapping("/index")
    public String toIndex(@RequestParam(required = false,defaultValue = "1") String pageNum,
                          @RequestParam(required = false,defaultValue = "8")String pageSize, Model model){
//        //取所有留言信息
//        List<Message> msglist = bookService.msglist();
        if (pageNum.equals("0")) pageNum = "1";
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        Page<Message> msglist = bookService.msglist();
        PageInfo<Message> pageInfo = msglist.toPageInfo();
        //按日期排序
        model.addAttribute("msglist",msglist);
        model.addAttribute("pageinfo",pageInfo);
        return "guestbook/test";
    }
//添加留言
    @RequestMapping("/addmsg")
    public String addmsg(Message message,Model model){
        //日期格式化后存入数据库
        Date date = new Date();
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        message.setCreatetime(sim.format(date));
        bookService.insertmsg(message);
        return "redirect:/book/index";
    }

    @RequestMapping("/reply")
    public String reply(String replymsg,String bookid){
        bookService.reply(replymsg,bookid);
        return "redirect:/book/index";
    }

    @RequestMapping("/delmsg")
    public String delmsg(String bookid){
        bookService.delmsg(bookid);
        return "redirect:/book/index";
    }

}
